<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script type="text/javascript" src="CommonUtil/CommonUtil.js"></script>
    <script type="text/javascript" charset="utf-8">
        /**
         * 代理模式（proxy）
         * 代理也是对象，它的目的就是为了节制（控制)对本体对象的访问
         */
        //图书馆，（本体对象，实例化本体对象需要消耗很多的资源）
        var LibraryInterface = new BH.Interface(
            'LibraryInterface',
            [
                'addBook',
                'findBook',
                'checkOutBook',
                'returnBook'
            ]);
        var Book = function (id,title,author) {
            this.id = id;
            this.title = title;
            this.author = author;
        };
        var Library = function (books) {
            this.books = books;
        };
        Library.prototype = {
            constructor:Library,
            addBook:function (book) {
                this.books[id] = book;
            },
            findBook:function (id) {
                if(this.books[id]){
                    return this.books[id];
                }
                return null;
            },
            checkOutBook:function (id) {
                //电脑登记，交押金
                this.findBook(id);
            },
            returnBook:function (book) {
                //电脑登记（已还）
                this.books[id] = book;
            }
        }
        //图书馆的代理对象
        var LibraryProxy = function (books) {
            alert('产生代理对象，并没有真正产生本体对象');
            this.books = books;
            this.library = null;
        }
        LibraryProxy.prototype = {
            constructor:Library,
            initializeLibrary:function () {
                alert('真正产生本体对象');
                if(this.library==null){
                    this.library = new Library(this.books);
                }
            },
            addBook:function (book) {
                this.initializeLibrary();
                this.library.addBook(book);
            },
            findBook:function (id) {
                this.initializeLibrary();
                return this.library.findBook(id);
            },
            checkOutBook:function (id) {
                this.initializeLibrary();
                return this.library.checkOutBook(id);
            },
            returnBook:function (book) {
                this.initializeLibrary();
                return this.library.returnBook(book);
            }
        }
        //实例化的代理对象
        /**
         *推迟本体对象实例化的时间
         *什么时间具体去做事情了，再去实例化它。
         */
        var proxy = new LibraryProxy({
            "01":new Book('01','java','z3'),
            "02":new Book('02','javascript','l4')
        });
        alert(proxy.findBook('02').author);
        //alert(proxy.findBook('01').title)
    </script>
</head>
<body>
</body>
</html>